import axios from 'axios';
//import {ta} from "element-plus/es/locale/index";
// import {ElMessage} from "element-plus";
const authItemName = "access_token"
const defaultFailure = (message, code, url) => {
    console.warn(`请求地址: ${url}, 状态码：${code}, 错误信息：${message}`)
    ElMessage.warning(message)
    ElMessage.warning(message)
    ElMessage.warning(message)
}
function internalPost(url, data, header, success, failure, error = defaultError) {
    axios.post(url, data, {headers: header}).then(({data}) => {
        if (data.code === 200) {
            success(data.data)
        } else {
            failure(data.message, data.code, url)
        }
    }).catch(err => error(err))
}
const defaultError = (err) => {
    console.error(err)
    ElMessage.warning('发生了一些错误，请联系管理员')

}
function takeAccessToken() {
   // console.log("test1:  "+ sessionStorage.getItem(authItemName))
    let str = localStorage.getItem(authItemName) || sessionStorage.getItem(authItemName);
    if(!str){
        console.log("no token")
        return null;}
   // console.log("takeAccessToken str got the token:    "+ str)
    const authObj = JSON.parse(str)
   // console.log("takeAccessToken authObj got the token:    "+ authObj.token)
   if(authObj.exprie <= new Date()){
       deleteAccessToken()
       ElMessage.warning('登录状态已过期，请重新登录')
       return null
   }
    if(authObj.token!=null){
        console.log("takeAccessToken(),success!"+authObj.token)
    } else {
        console.log("takeAccessToken,no token")
    }
   // console.log("takeAccessToken got the token:    "+ sessionStorage.getItem(authItemName))
    console.log("authObj.token    "+ sessionStorage.getItem(authItemName))
    return authObj.token
}


function storeAccessToken(token, remember, exprie) {
    const authObj = {
        token: token,
        exprie: exprie
    }
    const str = JSON.stringify(authObj)
    if (remember){
            localStorage.setItem(authItemName, str)
           // console.log("localStoraage,success!")
    }
    else{
        sessionStorage.setItem(authItemName, str)
      //  console.log("sessionStoraage,success!")
    }
   console.log("storeAccessToken got the token:    "+ sessionStorage.getItem(authItemName))
}
function deleteAccessToken() {
    console.log("deleteAccessToken")
    localStorage.removeItem(authItemName)
    sessionStorage.removeItem(authItemName)
}
function accessHeader()
{
    const token = takeAccessToken();
    if(token){
        console.log(" accessHeader got the token： "+ takeAccessToken())
    }else {
        console.log("accessHeader got no token")
    }
    return token ? {
      'Authorization': `Bearer ${takeAccessToken()}`
     } : {
     }
}
function internalGet(url,header, success, failure, error = defaultError) {
    axios.get(url, {
        headers: header
    }).then(({data}) => {
        if (data.code === 200) {
            success(data.data)
        } else {
            failure(data.message, data.code, url)
        }
    }).catch(err => error(err))
}
function get( url,success ,failure= defaultFailure){
    console.log("get："+ accessHeader().Authorization)
    console.log("token: "+accessHeader().token)
     internalGet(url,accessHeader(),success,failure)
}
function post(url,data,success,failure=defaultFailure){
    internalPost(url,data,accessHeader(),success,failure)
}
function login(username, password, remember, success, failure = defaultFailure) {
    internalPost('/api/auth/login',
        {
            username: username,
            password: password
        },
        {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        (data) => {
            storeAccessToken(data.token, remember, data.exprie)
            ElMessage.success(`登录成功,欢迎 ${data.username} 来到我们的系统`)
            success(data)
        },
        failure)
}

function logout(success,failure = defaultFailure) {
    get('/api/auth/logout',
        () => {
            deleteAccessToken()

            ElMessage.success('退出成功, 欢迎下次再来')
            // ElMessage.warning('退出成功, 欢迎下次再来')
            success()
        }, failure)

}
function unauthorized(){

   return !takeAccessToken();

}
export  {login, logout,get,post,unauthorized}

